<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script>
		/**
		 * Definition for singly-linked list.
		 * function ListNode(val, next) {
		 *     this.val = (val===undefined ? 0 : val)
		 *     this.next = (next===undefined ? null : next)
		 * }
		 */
		/**
		 * @param {ListNode} l1
		 * @param {ListNode} l2
		 * @return {ListNode}
		 */
		// 输入：l1 = [2,4,3], l2 = [5,6,4]
		// 输出：[7,0,8]
		// 解释：342 + 465 = 807.
		let list1 = new ListNode(2,new ListNode(4,new ListNode(3)));
		let list2 = new ListNode(5,new ListNode(6,new ListNode(4)));
		function ListNode(val, next) {
		    this.val = (val===undefined ? 0 : val)
		    this.next = (next===undefined ? null : next)
		}
		var addTwoNumbers = function(l1, l2) {
		    const l3 = new ListNode(0) // 定义一个链表来存放结果
		    let p1 = l1 // 指向链表1的头部
		    let p2 = l2 // 指向链表2的头部
		    let p3 = l3
		    let carry = 0 // 进位的数，即留到下一轮相加的数
		    while(p1 || p2) {
		        // 这两个三元判断是为了防止相加的两个数长度不同
		        const v1 = p1 ? p1.val : 0
		        const v2 = p2 ? p2.val : 0
		        const val = v1 + v2 + carry
		        carry = Math.floor(val / 10)
		        p3.next = new ListNode(val % 10)
		        if(p1) p1 = p1.next
		        if(p2) p2 = p2.next
		        p3 = p3.next
		    }
		    if(carry) {
		        p3.next = new ListNode(carry)
		    }
		    return l3.next
		};
		console.log(list1,list2);
		console.log(addTwoNumbers(list1,list2));
		</script>
	</body>
</html>
